package com.itheima.controller;

import com.itheima.domain.Answer;
import com.itheima.domain.Likes;
import com.itheima.domain.Question;
import com.itheima.domain.User;
import com.itheima.service.AnswerService;
import com.itheima.service.LikesService;
import com.itheima.service.QuestionService;
import com.itheima.service.UserService;
import com.itheima.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/ques")
public class QuestionController {

    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private UserService userService;
    @Autowired
    private LikesService likesService;

    @RequestMapping("/form")
    public String form(){
        return "questionForm";
    }

//    @RequestMapping("/detail")
//    public String detail(){
//        return "detail";
//    }

    @RequestMapping("/save")
    public String save(Question question, HttpSession session){
        System.out.println("question = " + question);
        //TODO 发表失败的处理
        questionService.save(question,session);
            return "redirect:/index";

    }

    @RequestMapping("/detail")
    public String detail(Integer qid, Model model,HttpSession session){



        Question question = questionService.getById(qid);
        //获取该问题的回复
        List<Answer> answerList = answerService.getByQid(qid);

        //得到评论者的信息并放入answer中
        Integer uid = question.getUid();
        User autor = userService.getById(uid);
        for (Answer answer:answerList) {
            if(session.getAttribute("user") != null) {
                User user1 = (User) session.getAttribute("user");
                int uid1 = user1.getUid();
                Likes byId = likesService.getById(new Likes(answer.getAid(), uid1));
                if(byId == null){
                    answer.setFlag(0);
                }else {
                    answer.setFlag(1);
                }
            }

            Integer answereruid = answer.getUid();
            User user = userService.getById(answereruid);
            answer.setUser(user);
        }

        int answeredCount = answerService.answerCount(qid);
        model.addAttribute("question",question);
        model.addAttribute("answerList",answerList);
        model.addAttribute("autor",autor);
        model.addAttribute("answeredCount",answeredCount);
        return "detail";
    }

    @RequestMapping("/deleteQue")
    public String deleteQue(Integer qid){
        questionService.delete(qid);

        return "redirect:/index";
    }



}
